using System;
using System.Web.Mvc;
using Autofac.Integration.Mvc;
using Limestone;

namespace SampleSite.Areas.Limestone.Models
{

    [ModelBinderType(typeof(Field))]
    public class FieldBinder : DefaultModelBinder
    {
        // TODO this should ideally reside in the Limestone assembly but for some reason Autofac wont bind to it properly
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var fieldTypeName = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".ModelType"];

            var field = FieldFactory.CreateField(fieldTypeName);

            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => field,
                                                                                             field.GetType());
            return field;
        }
    }
}